#!/bin/bash

set -e # fail early

shopt -s extglob  # extended glob pattern

function die() {
  echo "Error: " $*
  echo
  echo "Usage: $0 [apk] <version>"
  echo "Automatically sign [A-Z].apk"
  exit 1
}

# Try to use AAPT on first APK to guess the version number
AAPT=( ~/*sdk/build-tools/*/aapt.exe )
AAPT="${AAPT}"  # convert first's array value into its own value
if [[ ! -x "$AAPT" ]]; then
    die "Failed to find aapt.exe"
fi

ZIPALIGN=( ~/*sdk/tools/zipalign.exe )
ZIPALIGN="${ZIPALIGN}"
if [[ ! -x "$ZIPALIGN" ]]; then
    die "Failed to find zipalign.exe"
fi

function get_sdk_info() {
    local SRC="$1"
    LEAF=$(basename $SRC)

    VERS=$("$AAPT" dump badging "$SRC" | sed -n "/versionName/s/.*versionName='\(.*\)'/\1/p")
    echo "[$LEAF] Found version $VERS"
    [ -z "$VERS" ] && die "[$LEAF] Missing version number in aapt badging"

    VERS="${VERS/ Beta /b}"
    VERS="${VERS/ \(Beta\)/b}"
    VERS="${VERS}_"

    MIN_API=$("$AAPT" dump badging "$SRC" | sed -n "/sdkVersion/s/.*sdkVersion:'\(.*\)'/\1/p")
    echo "[$LEAF] Found min-sdk-version $MIN_API"
    [ -z "$MIN_API" ] && die "[$LEAF] Missing min-sdk-version in aapt badging"
    return 0
}

function process() {
	SRC="$1"
    LEAF=$(basename $SRC)
    echo
    echo "#### Process $LEAF"
    echo
    
    get_sdk_info "$SRC"     # fills $VERS (version name e.g. "1.11.12") and MIN_API (e.g. "3")
    MIN_API=$(printf "%02d" "$MIN_API")

	BASE="${SRC/.apk/}"
	BASE="${BASE/-*/}"
	
	DATE=$(date +%Y%m%d)
	N=1
	while /bin/true; do
		EXT=$(python -c "print chr(96+$N)")
		DEST="${BASE}_api${MIN_API}_v${VERS}${DATE}${EXT}.apk"
		[ ! -e "$DEST" ] && break
		N=$((N+1))
		[ "$N" == "27" ] && die "$DEST exists, can't generate higher letter."
	done

	echo "[$LEAF] Dest: $DEST"
    LEAF=$DEST
	
	ALIAS="${USER/p*/lf}2"	
	echo "[$LEAF] Signing with alias $ALIAS"
	
	jarsigner -verbose -keystore $(cygpath -w ~/*-release-*.keystore) "$SRC" $ALIAS
	
	SIZE1=$(stat -c "%s" "$SRC")
	
    echo "[$LEAF] Running $ZIPALIGN"
    "$ZIPALIGN" -f -v 4 "$SRC" "$DEST" && rm -v "$SRC"

	SIZE2=$(stat -c "%s" "$DEST")
	
	echo "[$LEAF] Has been signed and zipaligned (added $((SIZE2-SIZE1)) bytes)" 
    return 0
}

APK=( [S]+([^_]).apk )
if [[ "${1/.apk/}" != "$1" ]]; then
    APK="$1"
	shift
fi


for i in "${APK[@]}" ; do
    if [ ! -f "$i" ]; then
        die "Failed to find an APK to sign: $i"
    fi
	if [ -f "$i" ]; then
		if unzip -l "$i" | grep -qa ANDROID; then
			echo "ERROR: $i has a DEBUG KEY."
			exit 1
		fi

		process "$i"
	fi
done
